package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.GetPrice;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.entity.PayResult;
import dhm.com.hpx.entity.WacherBean;
import dhm.com.hpx.utils.SpUtils;

public class MemberActivity extends BaseActivity implements LoginContract.IView, IWXAPIEventHandler {

    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.taocanName)
    TextView taocanName;
    @BindView(R.id.btn_bojin)
    Button btnBojin;
    @BindView(R.id.bojins)
    LinearLayout bojins;
    @BindView(R.id.pay_activation)
    LinearLayout pay_activation;
    @BindView(R.id.eleven)
    LinearLayout eleven;
    @BindView(R.id.seven)
    LinearLayout seven;
    @BindView(R.id.money_bo)
    TextView moneyBo;
    @BindView(R.id.btn_huangjin)
    Button btnHuangjin;
    @BindView(R.id.huangjin)
    LinearLayout huangjin;
    @BindView(R.id.pay_alipay)
    LinearLayout pay_alipay;
    @BindView(R.id.pay_wechat)
    LinearLayout pay_wechat;
    @BindView(R.id.money_bai)
    TextView moneyBai;
    @BindView(R.id.huiyuan)
    TextView huiyuan;
    @BindView(R.id.btn_baijin)
    Button btnBaijin;
    @BindView(R.id.baijin)
    LinearLayout baijin;
    @BindView(R.id.coupontishi)
    TextView coupontishi;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.wechat_check)
    ImageView wechat_check;
    @BindView(R.id.alipay_check)
    ImageView alipay_check;
    @BindView(R.id.activation_check)
    ImageView activation_check;
    private String uid;

    private PressenterImpl pressenter;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult(((Map<String, String>) msg.obj));
                    String result1 = payResult.getResult();
                    if (payResult.getResultStatus().equals("9000")) {
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MemberActivity.this, MainActivity.class);
                        intent.putExtra("paySuccess", 1);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), payResult.getMemo(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
            }
        }
    };
    private String receive_id;
    private String title;
    private String with_amount="0";
    private String amount="0";
    private float monthPrice;
    private float seasonPrice;
    private float yearPrice;


    @Override
    protected int getLayout() {
        return R.layout.activity_member;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);

        showPopwindow();
        getWindow().setStatusBarColor(getResources().getColor(R.color.member));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
//            getWindow().getDecorView().setSystemUiVisibility(View.);

            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);

        }

        receive_id = getIntent().getStringExtra("receive_id");
        if (!receive_id.equals("0")){
            title = getIntent().getStringExtra("title");
            with_amount = getIntent().getStringExtra("with_amount");
            amount = getIntent().getStringExtra("amount");
            coupontishi.setText(title);
        }

        uid = SpUtils.getString(this, "uid");

        pressenter=new PressenterImpl();
        pressenter.attachView(this);

        Map<String,String> map=new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid",uid);

        pressenter.sendMessage(this,Constant.get_userinfo,map, GetUserInfoBean.class);

    }

    @Override
    protected void initData() {

    }

    private String payFrom="1";

    private String payType="3";

    @OnClick({R.id.back,R.id.sure, R.id.btn_bojin,  R.id.pay_activation, R.id.bojins, R.id.btn_huangjin, R.id.huangjin, R.id.btn_baijin, R.id.baijin, R.id.lin_coupon, R.id.pay_wechat, R.id.pay_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_bojin:
                break;
            case R.id.sure:
                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("payType", payType);
                map.put("payFrom",payFrom);
                float coupon = Float.parseFloat(with_amount);
                float couponj = Float.parseFloat(amount);
                switch (payType){
                    case "1":
                        if (with_amount.equals("0")){
                            map.put("orderMoney",""+monthPrice);
                            map.put("is_coupon","0");
                        }else if (coupon>monthPrice){
                            Toast.makeText(this, "此优惠券不可使用", Toast.LENGTH_SHORT).show();
                            map.put("orderMoney",""+monthPrice);
                            map.put("is_coupon","0");
                        }else {
                            map.put("is_coupon","1");
                            map.put("orderMoney",(monthPrice-couponj)+"");
                            map.put("receive_id",receive_id);
                        }
                        break;
                    case "2":
                        if (with_amount.equals("0")){
                            map.put("orderMoney",""+seasonPrice);
                            map.put("is_coupon","0");
                        }else if (coupon>seasonPrice){
                            Toast.makeText(this, "此优惠券不可使用", Toast.LENGTH_SHORT).show();
                            map.put("orderMoney",""+seasonPrice);
                            map.put("is_coupon","0");
                        }else {
                            map.put("is_coupon","1");
                            map.put("orderMoney",(seasonPrice-couponj)+"");
                            map.put("receive_id",receive_id);
                        }
                        break;
                    case "3":
                        if (with_amount.equals("0")){
                            map.put("orderMoney",""+yearPrice);
                            map.put("is_coupon","0");
                        }else if (coupon>yearPrice){
                            Toast.makeText(this, "此优惠券不可使用", Toast.LENGTH_SHORT).show();
                            map.put("orderMoney",""+yearPrice);
                            map.put("is_coupon","0");
                        }else {
                            map.put("is_coupon","1");
                            map.put("orderMoney",(yearPrice-couponj)+"");
                            map.put("receive_id",receive_id);
                        }
                        break;
                    default:
                }
                switch (payFrom){
                    case "1":
                        pressenter.sendMessage(MemberActivity.this,Constant.create_order,map,WacherBean.class);
                        break;
                    case "2":
                        pressenter.sendMessage(MemberActivity.this,Constant.create_order,map,String.class);
                        break;
                    case "3":
                        setBackgroundAlpha(0.5f);
                        popWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
                        break;
                    default:
                }
                break;
            case R.id.bojins:
                payType="3";
                bojins.setBackgroundResource(R.drawable.member_checks);
                huangjin.setBackgroundResource(R.drawable.member_checkn);
                baijin.setBackgroundResource(R.drawable.member_checkn);
                eleven.setVisibility(View.VISIBLE);
                seven.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_huangjin:
                break;
            case R.id.huangjin:
                payType="2";
                huangjin.setBackgroundResource(R.drawable.member_checks);
                bojins.setBackgroundResource(R.drawable.member_checkn);
                baijin.setBackgroundResource(R.drawable.member_checkn);
                eleven.setVisibility(View.INVISIBLE);
                seven.setVisibility(View.INVISIBLE);
                break;
            case R.id.btn_baijin:
                break;
            case R.id.baijin:
                payType="1";
                baijin.setBackgroundResource(R.drawable.member_checks);
                bojins.setBackgroundResource(R.drawable.member_checkn);
                huangjin.setBackgroundResource(R.drawable.member_checkn);
                eleven.setVisibility(View.INVISIBLE);
                seven.setVisibility(View.INVISIBLE);
                break;
            case R.id.lin_coupon:
                Intent intent=new Intent(MemberActivity.this,CouponActivity.class);
                intent.putExtra("type","2");
                startActivityForResult(intent,2);
                break;
            case R.id.pay_wechat:
                payFrom="1";
                activation_check.setBackgroundResource(R.mipmap.message_typen);
                alipay_check.setBackgroundResource(R.mipmap.message_typen);
                wechat_check.setBackgroundResource(R.mipmap.message_types);
                pay_wechat.setBackgroundResource(R.drawable.member_checks);
                pay_alipay.setBackgroundResource(R.drawable.member_checkn);
                pay_activation.setBackgroundResource(R.drawable.member_checkn);
                break;
            case R.id.pay_alipay:
                payFrom="2";
                activation_check.setBackgroundResource(R.mipmap.message_typen);
                wechat_check.setBackgroundResource(R.mipmap.message_typen);
                alipay_check.setBackgroundResource(R.mipmap.message_types);
                pay_alipay.setBackgroundResource(R.drawable.member_checks);
                pay_wechat.setBackgroundResource(R.drawable.member_checkn);
                pay_activation.setBackgroundResource(R.drawable.member_checkn);
                break;
            case R.id.pay_activation:
                payFrom="3";
                wechat_check.setBackgroundResource(R.mipmap.message_typen);
                alipay_check.setBackgroundResource(R.mipmap.message_typen);
                activation_check.setBackgroundResource(R.mipmap.message_types);
                pay_alipay.setBackgroundResource(R.drawable.member_checkn);
                pay_activation.setBackgroundResource(R.drawable.member_checks);
                pay_wechat.setBackgroundResource(R.drawable.member_checkn);
                break;
            default:
        }
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfoBean){
            GetUserInfoBean getUserInfoBean= (GetUserInfoBean) data;
            if (getUserInfoBean.getCode()==1){
                image.setImageURI(Constant.PATH+getUserInfoBean.getData().getHeadsmall());
                nick.setText(getUserInfoBean.getData().getUser_nickname());

                userType = getUserInfoBean.getData().getUserTypeName();
                if (getUserInfoBean.getData().getUserType() > 0) {
                    if (getUserInfoBean.getData().getUser_validity().equals("0")) {
                        userType = getUserInfoBean.getData().getUserTypeName()+"    "+getUserInfoBean.getData().getUser_validity_time();
                    } else if (getUserInfoBean.getData().getUserType() == 1) {
                        userType = "月卡会员  有效期至:"+getUserInfoBean.getData().getUser_validity_time();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String date = sdf.format(new java.util.Date());
                        timeCompare(getUserInfoBean.getData().getUser_validity_time(), date);
                    } else if (getUserInfoBean.getData().getUserType() == 2) {
                        userType = "季卡会员  有效期至:"+getUserInfoBean.getData().getUser_validity_time();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String date = sdf.format(new java.util.Date());
                        timeCompare(getUserInfoBean.getData().getUser_validity_time(), date);
                    } else if (getUserInfoBean.getData().getUserType() == 3) {
                        userType = "年卡会员  有效期至:"+getUserInfoBean.getData().getUser_validity_time();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String date = sdf.format(new java.util.Date());
                        timeCompare(getUserInfoBean.getData().getUser_validity_time(), date);
                    }

                }


                huiyuan.setText(userType);

            }

            pressenter.sendMessage(MemberActivity.this,Constant.get_price,new HashMap<String, String>(), GetPrice.class);

        }else if (data instanceof WacherBean){
            if (data!=null){
                WacherBean wacherBean= (WacherBean) data;
                wxPay(wacherBean);
            }
        }else if (data instanceof String){
            if (data!=null){
                String orderInfo= (String) data;
                orderInfo=URLDecoder.decode(orderInfo);
                aliPay(orderInfo);
            }
        }else if (data instanceof GetPrice){
            GetPrice getPrice= (GetPrice) data;

            if (getPrice.getCode()==1){


                monthPrice = Float.parseFloat(getPrice.getData().getMonthPrice());
                seasonPrice = Float.parseFloat(getPrice.getData().getSeasonPrice());
                yearPrice = Float.parseFloat(getPrice.getData().getYearPrice());


                money.setText(yearPrice+"");
                moneyBo.setText(seasonPrice+"");
                moneyBai.setText(monthPrice+"");



            }

        }else if (data instanceof Bean){
            Bean bean= (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();

            initView();

        }

    }

    private String userType;
    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public String timeCompare(String startTime, String endTime) {
        int i = 0;
        //注意：传过来的时间格式必须要和这里填入的时间格式相同
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                //没过期
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                //过期
                userType = userType+"   已过期";
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //过期
                userType = userType+"   已过期";
                i = 3;
            }
        } catch (Exception e) {

        }

        return i + "";
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            receive_id=data.getStringExtra("receive_id");
            title=data.getStringExtra("title");
            with_amount=data.getStringExtra("with_amount");
            amount=data.getStringExtra("amount");
            coupontishi.setText(title);
        }
    }

    private void aliPay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MemberActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void wxPay(WacherBean wacherBean) {
        IWXAPI api = WXAPIFactory.createWXAPI(MemberActivity.this, Constant.Wx_APP_ID);
        api.handleIntent(getIntent(),MemberActivity.this);
        api.registerApp(Constant.Wx_APP_ID);
        PayReq req = new PayReq();

        req.appId = wacherBean.getAppid();
        req.partnerId = wacherBean.getPartnerid();
        req.prepayId = wacherBean.getPrepayid();
        req.packageValue = wacherBean.getPackageX();
        req.nonceStr = wacherBean.getNoncestr();
        req.timeStamp = wacherBean.getTimestamp();
        req.sign = wacherBean.getSign();
        api.sendReq(req);

    }



    @Override
    public void fail(String error) {

    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    final String TAG="微信支付结果";
    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = 0   支付成功");
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(this, "支付错误" + resp.errCode, Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = -1  支付错误");
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    Log.d(TAG, "onResp: resp.errCode = -2  用户取消");
                    Toast.makeText(this, "用户取消" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                default:
            }

            finish();//这里需要关闭该页面
        }
    }



    private PopupWindow popWindow;

    private void showPopwindow() {
        View popView = View.inflate(this, R.layout.user_activation, null);
        TextView cancle = popView.findViewById(R.id.cancle);
        TextView sure = popView.findViewById(R.id.sure);
        final EditText activation = popView.findViewById(R.id.activation);

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String activation_text = activation.getText().toString();
                if (activation_text!=null&&!activation_text.equals("")){
                    Map<String,String> map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("user_id",uid);
                    map.put("activation_code",activation_text);

                    pressenter.sendMessage(MemberActivity.this,Constant.user_activation,map, Bean.class);

                    popWindow.dismiss();

                }else {
                    Toast.makeText(MemberActivity.this, "请输入激活码", Toast.LENGTH_SHORT).show();
                }

            }
        });

        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }



    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }



}
